<!--
 * User: CHT
 * Date: 2020/5/27
 * Time: 9:52
-->
<template>
  <div style="display: flex;justify-content: space-between;">
    <div class="super-flow-base-demo">
      <super-flow
        ref="superFlow"
        :draggable='false'
        :node-list="nodeList"
        :linkAddable='false'
        :link-list="linkList"
        :origin="origin"
        :graph-menu="graphMenuList"
        :node-menu="nodeMenuList"
        :link-menu="linkMenuList"
        :enter-intercept="enterIntercept"
        :output-intercept="outputIntercept"
        @toJSON='toJSON'
        :link-desc="linkDesc">
        <template slot="node" slot-scope="{meta}">
          <div :class="`flow-node flow-node-${meta.prop}`">
            <header class="ellipsis">
              {{ meta.name }}
              <Checkbox v-if="meta.prop != 'end'" v-model="meta._check" @on-change='selectUpNode($event,meta)'></Checkbox>
              <!-- <input type="checkbox" v-if="meta.prop != 'end'" checked="meta._check" /> -->
            </header>
            <section>
              {{ meta.desc }}
            </section>
          </div>
        </template>
      </super-flow>
    </div>
    <div class="table-two-wrap">
      <Table border ref="selection" :columns="col" :data="taskList" style="width: 280px;" 
        @on-select='selectOne' @on-select-cancel='cancelOne'>
      </Table>
      <Table border ref="selection" :columns="col" :data="colTaskList" style="width: 280px;" 
        @on-select='selectOne' @on-select-cancel='cancelOne'>
      </Table>
    </div>
  </div>
  
</template>

<script>
  import {taskList,checkTaskList} from '@/api/train.js'
  const drawerType = {
    node: 0,
    link: 1
  }
  function GenNonDuplicateID(randomLength){  // 随机一个id
    return Number(Math.random().toString().substr(3,randomLength) + Date.now()).toString(36)
  }
export default {
  data () {
    return {
      sceneID:this.$route.query.id,
      testId:this.$route.query.testId,
      drawerType,
      drawerConf: {
        title: '',
        visible: false,
        type: null,
        info: null,
        open: (type, info) => {
          const conf = this.drawerConf
          conf.visible = true
          conf.type = type
          conf.info = info
          if (conf.type === drawerType.node) {
            conf.title = '节点'
            this.$set(this.nodeSetting, 'name', info.meta.name)
            this.$set(this.nodeSetting, 'desc', info.meta.desc)
          }
        },
        cancel: () => {
          this.drawerConf.visible = false
        }
      },
      nodeSetting: {
        name: '',
        desc: ''
      },
      origin: [800, 400],
      nodeList: [
        {
          'id': 'nodeS3WgFnzCI15X58Qw',
          'width': 100,
          'height': 80,
          'coordinate': [-750, -50],
          'meta': {
            'prop': 'start',
            'name': '开始节点',
            _check:false,
            'id': 'nodeS3WgFnzCI15X58Qw',
            'coordinate': [-750, -50],
          },
        },
        // {
        //   'id': 'nodeni9QOqT3mI7hsMau',
        //   'width': 100,
        //   'height': 80,
        //   'coordinate': [-550, -50],
        //   'meta': {
        //     'prop': 'approval',
        //     'name': '流程节点'
        //   }
        // },
        // {
        //   'id': 'nodeni9QOqT3mI7hsMa2',
        //   'width': 100,
        //   'height': 80,
        //   'coordinate': [-350, -50],
        //   'meta': {
        //     'prop': 'approval',
        //     'name': '流程节点'
        //   }
        // },
        // {
        //   'id': 'nodeDhVU6w2KbEnJCjZs',
        //   'width': 100,
        //   'height': 80,
        //   'coordinate': [-150, -50],
        //   'meta': {
        //     'prop': 'end',
        //     'name': '结束节点'
        //   }
        // },
      ],
      linkList: [
        // {
        //   'id': 'linkcs9ZhumWeTHrtUy8',
        //   'startId': 'nodeS3WgFnzCI15X58Qw',
        //   'endId': 'nodeni9QOqT3mI7hsMau',
        //   'startAt': [100, 40],
        //   'endAt': [0, 25],
        //   'meta': null
        // },
        // {
        //   'id': 'linkcs9ZhumWeTHrtUy2',
        //   'startId': 'nodeS3WgFnzCI15X58Qw',
        //   'endId': 'nodeni9QOqT3mI7hsMa2',
        //   'startAt': [100, 40],
        //   'endAt': [0, 25],
        //   'meta': null
        // },
        // {
        //   'id': 'linkcs9ZhumWeTHrtUy1',
        //   'startId': 'nodeni9QOqT3mI7hsMa2',
        //   'endId': 'nodeDhVU6w2KbEnJCjZs',
        //   'startAt': [100, 40],
        //   'endAt': [0, 25],
        //   'meta': null
        // },
      ],
      graphMenuList: [
        // [
        //   {
        //     label: '开始节点',
        //     disable (graph) {
        //       return !!graph.nodeList.find(node => node.meta.prop === 'start')
        //     },
        //     selected: (graph, coordinate) => {
        //       const start = graph.nodeList.find(node => node.meta.prop === 'start')
        //       if (!start) {
        //         graph.addNode({
        //           width: 100,
        //           height: 80,
        //           coordinate: coordinate,
        //           meta: {
        //             prop: 'start',
        //             name: '开始节点'
        //           }
        //         })
        //       }
        //     }
        //   },
        //   {
        //     label: '流程节点',
        //     disable: false,
        //     selected: (graph, coordinate) => {
        //       graph.addNode({
        //         width: 160,
        //         height: 80,
        //         coordinate: coordinate,
        //         meta: {
        //           prop: 'approval',
        //           name: '流程节点'
        //         }
        //       })
        //     }
        //   },
        //   {
        //     label: '结束节点',
        //     disable (graph) {
        //       return !!graph.nodeList.find(point => point.meta.prop === 'end')
        //     },
        //     selected: (graph, coordinate) => {
        //       graph.addNode({
        //         width: 100,
        //         height: 80,
        //         coordinate: coordinate,
        //         meta: {
        //           prop: 'end',
        //           name: '结束节点'
        //         }
        //       })
        //     }
        //   }
        // ]
      ],
      nodeMenuList: [
        // [
        //   {
        //     label: '编辑',
        //     hidden (node) {
        //       let b = false
        //       if(node.meta.prop === 'start' ||  node.meta.prop === 'end' ){
        //         b = true
        //       }
        //       return b
        //     },
        //     selected: (node, coordinate) => {
        //       this.drawerConf.open(drawerType.node, node)
        //     }
        //   }
        // ],
        // [
        //   {
        //     label: '删除',
        //     disable: false,
        //     selected (node, coordinate) {
        //       // console.log(node)
        //       _this.removeNode(node)
        //       node.remove()
        //     }
        //   }
        // ]
      ],
      linkMenuList: [],
      // 任务列表
      col:[
          {
            title:'选择任务',
            type: 'selection',
            key:'_checked',
            align: 'center',
            width:60,
          },
          {
            title: '任务类型',
            key: 'taskType',
            width:90,
            render: (h, params) => {
              let text = ''
              if(params.row.taskType == 'train'){
                text = '训练'
              }else if(params.row.taskType == 'check'){
                text = '验证'
              }
              return h('div',text)
            }
          },
          {
              title: '任务名称',
              key: 'name',
              minWidth:120,
          },
      ],
      taskData:[],
      taskList:[],
      colTaskList:[],
      // 全选 / 单选
      currentSelectTask:[],
      // 当前选中的上一步节点信息
      upNodeInfo:[],
    }
  },
  created () {
    let _this = this
    _this.nodeMenuList = [
      [
        {
          label: '删除',
          disable: false,
          selected (node, coordinate) {
            if(node.meta.prop == 'start'){
              _this.$Message.info('不可删除开始节点！')
              return false
            }
            _this.removeNode(node)
            node.remove()
          }
        }
      ]
    ]
  },
  watch: {
    
  },
  mounted () {
    this.getTaskList()
    this.getColTaskList()
  },
  methods: {
    enterIntercept (formNode, toNode, graph) {
      const formType = formNode.meta.prop
      switch (toNode.meta.prop) {
        case 'start':
          return false
        case 'approval':
          return [
            'start',
            'approval',
            'condition',
            'cc'
          ].includes(formType)
        case 'condition':
          return [
            'start',
            'approval',
            'condition',
            'cc'
          ].includes(formType)
        case 'end':
          return [
            'approval',
            'cc'
          ].includes(formType)
        default:
          return true
      }
    },
    outputIntercept (node, graph) {
      return !(node.meta.prop === 'end')
    },
    linkDesc (link) {
      return link.meta ? link.meta.desc : ''
    },
    toJSON(data){
      
    },
    // 训练任务列表
    getTaskList(){
      let params = {
        pageIndex:1,
        pageSize:1000,
        trainingId:this.sceneID,
      }
      taskList(params)
      .then(res=>{
        if(res.data.code === 1){
            let items = res.data.data.records
            items.forEach(element => {
              element._checked = false
            });
            let endNode = {
              'id': 'nodeDhVU6w2KbEnJCjZs',
              'width': 80,
              'height': 50,
              'coordinate': [0, 0],
              'meta': {
                'prop': 'end',
                'name': '结束节点'
              },
              name:'结束节点',
              taskType:'结束节点',
              createTime:'null'
            }
            items.push(endNode)
            this.taskList = items
        }else{
            this.taskList = []
        }
      })
      .catch(err=>{
          console.log(err)
      })
    },
    // 验证任务列表
    getColTaskList(){
      let params = {
        pageIndex:1,
        pageSize:1000,
        trainingId:this.sceneID,
      }
      checkTaskList(params)
      .then(res=>{
          if(res.data.code === 1){
            let items = res.data.data.records
            items.forEach(element => {
              element._checked = false
            });
            this.colTaskList = res.data.data.items
          }else{
            this.colTaskList = []
          }
      })
      .catch(err=>{
          console.log(err)
      })
    },
    // 勾选前一节点
    selectUpNode(e,meta){
      for(let i=0;i<this.nodeList.length;i++){
        if(meta.id == this.nodeList[i].id){
          this.nodeList[i].meta._check = e
        }
      }
      let index = this.upNodeInfo.findIndex(item => item.id == meta.id);
      if(e && index < 0){
        this.upNodeInfo.push(meta)
      }else if(!e && index >= 0){
        this.upNodeInfo.splice(index,1);
      }
    },
    // 单选 取消
    selectOne(selection,row){
      let arr = []
      if(row.taskType == 'train' || row == '结束节点'){
        arr = this.taskList
      }else if(row.taskType == 'check'){
        arr = this.colTaskList
      }
      this.setSelected(arr,row.id,true)
      this.addTaskToProcess(row)
    },
    cancelOne(selection,row){
      let index = this.nodeList.findIndex(item => item.id == row.id);
      if(index >= 0){
        this.nodeList.splice(index,1);
        for(var i=this.linkList.length-1;i>=0;i--){
          if(this.linkList[i].endId == row.id){
            this.linkList.splice(i,1)
          }
        }
      }
    },
    // 将任务添加到流程图
    addTaskToProcess(row){
      if(this.upNodeInfo.length == 0){
        this.$Message.info({
          content:'请先勾选父节点',
          duration:3,
        })
        return false
      }
      let zeroNodeCoor = this.upNodeInfo[0].coordinate
      let zeroNodeId = this.upNodeInfo[0].id
      let nodeObj = {   // 如果勾选多个父节点，则新节点的位置以第一个父节点位置为准
        'id': GenNonDuplicateID(20),
        'width': 100,
        'height': 80,
        // 'coordinate': [-550, -50],
        'coordinate': this.setCoordinate(zeroNodeCoor,zeroNodeId),
        'meta': {
          'prop': 'approval',
          'name': '流程节点',
          desc:row.name,
          taskId:row.id,
          taskType:row.taskType,
          trainingId: row.trainingId,
        }
      }
      nodeObj.meta.id = nodeObj.id
      nodeObj.meta.coordinate = nodeObj.coordinate
      if(row.taskType == '结束节点'){
        nodeObj.meta.prop = 'end'
        nodeObj.meta.name = '结束节点'
        nodeObj.meta.taskType = '结束节点'
      }
      this.nodeList.push(nodeObj)
      for(let i=0;i<this.upNodeInfo.length;i++){
        let startNodeId = this.upNodeInfo[i].id
        let lineObj = {
          'id': GenNonDuplicateID(20),
          'startId': startNodeId,
          'endId': nodeObj.id,
          'startAt': [100, 40],
          'endAt': [0, 25],
          'meta': null
        }
        this.linkList.push(lineObj)
      }
    },
    // 计算新加节点的位置
    setCoordinate(arr,startId){
      let getLinkNum = this.linkList.filter(item=>{return item.startId == startId}).length
      if(getLinkNum == 0){
        return [arr[0]+200,arr[1]]
      }else{
        let parity = (getLinkNum%2) == 0 ?true:false  // 偶数  奇数
        let rows = parseInt((getLinkNum+1)/2)  // 判断新加节点放第几层
        return parity?[arr[0]+200,arr[1]+100*rows]:[arr[0]+200,arr[1]-100*rows]
      }
    },
    // 删除节点时同时从数组中移除
    removeNode(node){
      let index = this.nodeList.findIndex(item => item.id == node.id);
      this.nodeList.splice(index,1);
      // 改变数组中的选中状态
      let arr = []
      if(node.meta.taskType == 'train' || node.meta == '结束节点'){
        arr = this.taskList
      }else if(node.taskType == 'check'){
        arr = this.colTaskList
      }
      this.setSelected(arr,node.meta.taskId,false)
    },
    // 勾选或取消 设置check
    setSelected(arr,id,bool){
      arr.forEach(element => {
        if(element.id == id){
          element._checked = bool
        }
      });
    },
  }
}
</script>

<style>
.ellipsis {
  white-space   : nowrap;
  text-overflow : ellipsis;
  overflow      : hidden;
  word-wrap     : break-word;
}
.super-flow-base-demo {
  width            : 700px;
  height           : 700px;
  margin           : 0 auto;
  background-color : #f5f5f5;
  overflow         : scroll;
}
.super-flow-base-demo .super-flow {
    width  : 2000px;
    height : 1000px;
  }
  .super-flow__node .flow-node header{
    font-size   : 14px;
    height      : 32px;
    line-height : 32px;
    padding     : 0 12px;
    color       : #ffffff;
  }
  .super-flow__node .flow-node section{
    text-align  : center;
    line-height : 20px;
    overflow    : hidden;
    padding     : 6px 12px;
    word-break  : break-all;
  }
  .flow-node-start header{
    background-color : #55abfc;
  }
  .flow-node-condition header{
    background-color : #BC1D16;
  }
  .flow-node-approval header{
    background-color :  rgba(188, 181, 58, 0.76);
  }
  .flow-node-cc header{
    background-color : #30b95c;
  }
  .flow-node-end header{
    height           : 50px;
    line-height      : 50px;
    background-color : rgb(0, 0, 0);
  }
  .table-two-wrap{
    margin-left: 20px;
    width: 580px;
    max-height: 700px;
    overflow-y: auto;
    overflow-x: hidden;
    display: flex;
    justify-content: space-between;
  }
  .table-two-wrap .ivu-table-header .ivu-checkbox{
    display: none;
  }
</style>
